package com.xiaokaceng.openci.email;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.HtmlEmail;

import com.ibm.icu.text.SimpleDateFormat;
import com.xiaokaceng.openci.DefaultEmailNotSettingsException;
import com.xiaokaceng.openci.domain.Developer;
import com.xiaokaceng.openci.domain.EmailConfiguration;
import com.xiaokaceng.openci.domain.Project;
import com.xiaokaceng.openci.domain.ProjectDeveloper;
import com.xiaokaceng.openci.domain.Tool;
import com.xiaokaceng.openci.pojo.MailSendResult;

public class ProjectEmail {

	private static final String CHAREST = "UTF-8";

	private Project project;

	private Developer developer;

	public ProjectEmail(Project project, Developer developer) {
		this.project = project;
		this.developer = developer;
	}

	public MailSendResult send() {
		String htmlContent = createHtmlEmailContent();
		try {
			HtmlEmail htmlEmail = initHtmlEmail();
			htmlEmail.addTo(developer.getEmail());
			htmlEmail.setCharset(CHAREST);
			htmlEmail.setSubject("OPENCI-PLATFORM项目通知");
			htmlEmail.setHtmlMsg(htmlContent);
			htmlEmail.send();
			return MailSendResult.createSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return MailSendResult.createFailure(e.toString());
		}
	}

	private String createHtmlEmailContent() {
		return setMailContent(getProjectNoticeHtmlMail());
	}

	private String setMailContent(String projectNoticeHtmlMail) {
		projectNoticeHtmlMail = setDeveloeprName(projectNoticeHtmlMail);
		projectNoticeHtmlMail = setProjectName(projectNoticeHtmlMail);
		projectNoticeHtmlMail = setCreateDate(projectNoticeHtmlMail);
		projectNoticeHtmlMail = setTeamMembers(projectNoticeHtmlMail);
		projectNoticeHtmlMail = setIntegrationTools(projectNoticeHtmlMail);
		return projectNoticeHtmlMail;
	}

	private String setIntegrationTools(String projectNoticeHtmlMail) {
		StringBuffer stringBuffer = new StringBuffer();
		for (Tool each : project.getTools()) {
			stringBuffer.append("<span style=").append('"').append("margin-left: 60px;").append('"').append(">");
			stringBuffer.append(each.getToolConfiguration().getName()).append("&nbsp;&nbsp;访问地址:<a href='").append(each.getToolRequestAddress()).append("'>").append(each.getToolRequestAddress()).append("</a></span><br>");
		}
		return projectNoticeHtmlMail.replace("&{integrationTools}", stringBuffer.toString());
	}

	private String setTeamMembers(String projectNoticeHtmlMail) {
		StringBuffer stringBuffer = new StringBuffer();
		for (ProjectDeveloper each : project.getDevelopers()) {
			stringBuffer.append(each.getDeveloper().getName()).append("、");
		}
		return projectNoticeHtmlMail.replace("&{teamMembers}", stringBuffer.substring(0, stringBuffer.length() - 1));
	}

	private String setCreateDate(String projectNoticeHtmlMail) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return projectNoticeHtmlMail.replace("&{createDate}", dateFormat.format(project.getCreateDate()));
	}

	private String setProjectName(String projectNoticeHtmlMail) {
		return projectNoticeHtmlMail.replace("&{projectName}", project.getName());
	}

	private String setDeveloeprName(String projectNoticeHtmlMail) {
		return projectNoticeHtmlMail.replace("&{name}", developer.getName());
	}

	private String getProjectNoticeHtmlMail() {
		String configFileName = "ProjectNoticeHtmlMail.properties";
		InputStream is = this.getClass().getResourceAsStream("/" + configFileName);
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuilder builder = new StringBuilder();
		try {
			String line = null;
			while ((line = br.readLine()) != null)
				builder.append(line);
		} catch (IOException e) {
			throw new RuntimeException("read " + configFileName + " failure.", e);
		}
		return builder.toString();
	}

	private HtmlEmail initHtmlEmail() {
		EmailConfiguration emailConfiguration = getSystemDefaultConfiguration();
		HtmlEmail email = new HtmlEmail();
		email.setHostName(emailConfiguration.getSmtpAddress());
		email.setSmtpPort(emailConfiguration.getSmtpPort());
		email.setAuthenticator(new DefaultAuthenticator(emailConfiguration.getUsername(), emailConfiguration.getPassword()));
		email.setSSLOnConnect(false);
		try {
			if (emailConfiguration.getName() != null) {
				email.setFrom(emailConfiguration.getUsername(), emailConfiguration.getName());
			} else {
				email.setFrom(emailConfiguration.getUsername());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return email;
	}

	private EmailConfiguration getSystemDefaultConfiguration() {
		EmailConfiguration emailConfiguration = EmailConfiguration.getDefault();
		if (emailConfiguration != null) {
			return emailConfiguration;
		}
		throw new DefaultEmailNotSettingsException();
	}

}
